<?php
namespace App\Service\Admin;

use Illuminate\Support\Facades\DB;

class UtagService extends BaseService
{
    //用户标签

    /**
     * 列表
     */
    public function getList($uid)
    {
        $db = $this->dbConn($this->dbUtag)->where('del', 0)
            ->where('uid', $uid);
        $total = $db->count();
        $res = $db->orderBy('id', 'desc')->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $arys = [];
        foreach ($res as $k => $v) {
            $v = (array) $v;
            $arys[] = [
                'id' => $v['id'],
                'title' => $v['title'],
                'addtime' => $v['addtime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 添加
     * @param int $uid
     * @param string $title
     */
    public function add($uid, $title)
    {
        $res = (array) $this->dbConn($this->dbUtag)
            ->where('del', 0)
            ->where('uid', $uid)
            ->where('title', $title)
            ->first();
        if (!empty($res)) {
            return $this->toback(-2, '存在同名标签');
        }
        $this->dbConn($this->dbUtag)->insertGetId([
            'uid' => $uid, 'title' => $title, 'addtime' => toDate(),
        ]);
        return $this->toback();
    }

    /**
     * 删除
     * @param int $id
     */
    public function del($id)
    {
        $res = (array) $this->dbConn($this->dbUtag)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        $this->dbConn($this->dbUtag)->where('id', $id)->update(['del' => 1, 'deltime' => toDate()]);
        return $this->toback();
    }
}